package de.tum.in.elitese.wahlsys.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JOptionPane;

/**
 * This is class reads the properties and offers an easy access to them.
 * 
 * @author Christoph Frenzel
 * 
 */
public class DbProperties {
	public static final String DRIVER = "driver";

	public static final String MAX_BATCH_COUNT = "max_batch_count";

	public static final String URL = "url";

	private static Properties DB_PROPERTIES;

	private static final String PROPERTIES_FILE = "conf/wahlsystem.properties";

	/**
	 * Singleton
	 * 
	 * @return the Properties for the DB application.
	 */
	public static Properties getProperties() {
		if (DB_PROPERTIES == null) {
			DB_PROPERTIES = loadProperties();
		}
		return DB_PROPERTIES;
	}

	/**
	 * Returns the value of the property identified by the given key.
	 * 
	 * @param key
	 * @return the value of the key
	 */
	public static String getProperty(String key) {
		if (key == null) {
			throw new IllegalArgumentException("key must not be null");
		}

		return getProperties().getProperty(key);
	}

	/**
	 * Loads the Properties from the file and returns them.
	 * 
	 * @return the loaded properties
	 */
	private static Properties loadProperties() {
		FileInputStream reader = null;

		// open file
		try {
			reader = new FileInputStream(PROPERTIES_FILE);
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null, "Properies file 'db.properties' not found.", "Properties file not found.", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
			System.exit(-1);
		}
		Properties properties = new Properties();

		// load properties from file
		try {
			properties.load(new BufferedInputStream(reader));
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Properies file 'db.properties' could not be read.", "Properties file could not be read.", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
			System.exit(-1);
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "Properies file 'db.properties' could not be closed.", "Properties file could not be closed.", JOptionPane.ERROR_MESSAGE);
				System.exit(-1);
				e.printStackTrace();
			}
		}
		return properties;
	}
}
